<template>
  <div class="login-container">
    <div class="login-wrapper">
      <div class="login-header">
        <div class="logo">
          <img src="https://www.bilibili.com/favicon.ico" alt="bilibili" />
          <span>B站下载器</span>
        </div>
      </div>
      
      <div class="login-content card">
        <h2 class="login-title">扫码登录</h2>
        <p class="login-subtitle">请使用哔哩哔哩客户端扫码登录</p>
        
        <div class="qr-section" v-if="!qrCodeUrl && !loading">
          <el-button 
            type="primary" 
            size="large" 
            @click="generateQRCode"
            class="generate-btn"
          >
            <el-icon><Refresh /></el-icon>
            生成登录二维码
          </el-button>
        </div>
        
        <div class="qr-section" v-if="loading">
          <div class="loading-wrapper">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>正在生成二维码...</p>
          </div>
        </div>
        
        <div class="qr-section" v-if="qrCodeUrl && !loading">
          <div class="qr-code-wrapper">
            <img :src="qrCodeUrl" alt="登录二维码" class="qr-code" />
            <div class="qr-status" :class="statusClass">
              <el-icon v-if="loginStatus === 'scanning'"><View /></el-icon>
              <el-icon v-if="loginStatus === 'success'"><Check /></el-icon>
              <el-icon v-if="loginStatus === 'expired'"><Close /></el-icon>
              <p>{{ statusText }}</p>
            </div>
          </div>
          
          <div class="qr-actions">
            <el-button @click="generateQRCode" :loading="refreshing">
              <el-icon><Refresh /></el-icon>
              刷新二维码
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh, Loading, View, Check, Close } from '@element-plus/icons-vue'
import { apiMethods } from '../utils/api'

import QRCode from 'qrcode'
import {setSessData} from "../utils/auth";
export default {
  name: 'Login',
  components: {
    Refresh,
    Loading,
    View,
    Check,
    Close
  },
  setup() {
    const router = useRouter()

    const loading = ref(false)
    const refreshing = ref(false)
    const loginStatus = ref('waiting') // waiting, scanning, success, expired
    const pollTimer = ref(null)
    
    const statusClass = ref('')
    const statusText = ref('请使用哔哩哔哩客户端扫码')



    const qrCodeUrl = ref('')

// 生成二维码
    const generateQRCode = async () => {
      try {
        loading.value = true
        refreshing.value = true

        const response = await apiMethods.applyLoginQR()
        if (response.data.code === 0) {
          // 这里是登录链接，不是图片
          const qrContent = response.data.data.url
          qrCodeUrl.value = await QRCode.toDataURL(qrContent) // 生成 base64 图片
          
          // 重置状态
          loginStatus.value = 'waiting'
          statusText.value = '请使用哔哩哔哩客户端扫码'
          statusClass.value = ''
          
          // 开始轮询扫码状态
          startPolling()
        } else {
          ElMessage.error('获取二维码失败: ' + response.data.message)
        }
      } catch (error) {
        ElMessage.error('网络错误，请检查后端服务是否启动')
        console.error('生成二维码失败:', error)
      } finally {
        loading.value = false
        refreshing.value = false
      }
    }
    
    // 开始轮询扫码状态
    const startPolling = () => {
      clearPolling()
      pollTimer.value = setInterval(async () => {
        try {
          console.log('正在检查扫码状态...')
          const response = await apiMethods.scanLogin()
          console.log('扫码检查响应:', response.data)
          
          if (response.data.code === 0) {
            // 登录成功
            const sessData = response.data.sessdata
            console.log('登录成功，获取到SESSDATA:', sessData ? '有值' : '无值')

            if (sessData) {
              loginStatus.value = 'success'
              statusText.value = '登录成功，正在跳转...'
              statusClass.value = 'success'
              
              setSessData(sessData)
              clearPolling()
              
              console.log('准备跳转到dashboard')
              
              // 等待Cookie设置完成后再跳转
              setTimeout(() => {
                console.log('开始路由跳转')
                router.push('/dashboard').then(() => {
                  console.log('路由跳转成功')
                }).catch((error) => {
                  console.error('路由跳转失败:', error)
                  console.log('使用强制跳转')
                  window.location.href = '/dashboard'
                })
              }, 1000) // 增加延迟时间，确保Cookie设置完成
            }
          } else if (response.data.code === 86101) {
            // 未扫码
            console.log('等待扫码...')
            loginStatus.value = 'waiting'
            statusText.value = '请使用哔哩哔哩客户端扫码'
            statusClass.value = ''
          } else if (response.data.code === 86090) {
            // 已扫码，等待确认
            console.log('已扫码，等待确认...')
            loginStatus.value = 'scanning'
            statusText.value = '扫码成功，请在手机上确认登录'
            statusClass.value = 'scanning'
          } else if (response.data.code === 86038) {
            // 二维码过期
            console.log('二维码已过期')
            loginStatus.value = 'expired'
            statusText.value = '二维码已过期，请刷新'
            statusClass.value = 'expired'
            clearPolling()
          } else {
            console.log('未知状态码:', response.data.code)
          }
        } catch (error) {
          console.error('轮询登录状态失败:', error)
        }
      }, 2000)
    }
    
    // 清除轮询
    const clearPolling = () => {
      if (pollTimer.value) {
        clearInterval(pollTimer.value)
        pollTimer.value = null
      }
    }
    
    onMounted(() => {
      // 路由守卫已经处理了登录状态检查
      // 如果能进入这个组件，说明用户未登录
      console.log('进入登录页面，用户未登录')
      
      // 可以自动生成二维码
      // generateQRCode()
    })
    
    onUnmounted(() => {
      clearPolling()
    })
    
    return {
      qrCodeUrl,
      loading,
      refreshing,
      loginStatus,
      statusClass,
      statusText,
      generateQRCode
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-wrapper {
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.logo img {
  width: 32px;
  height: 32px;
}

.login-content {
  padding: 40px;
  text-align: center;
  background: white;
  border-radius: 16px;
}

.login-title {
  font-size: 28px;
  font-weight: 600;
  color: #18191c;
  margin-bottom: 8px;
}

.login-subtitle {
  color: #61666d;
  margin-bottom: 30px;
  font-size: 14px;
}

.qr-section {
  margin: 30px 0;
}

.generate-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
}

.loading-wrapper {
  padding: 40px 0;
  color: #61666d;
}

.loading-wrapper .el-icon {
  font-size: 32px;
  margin-bottom: 16px;
}

.qr-code-wrapper {
  position: relative;
  display: inline-block;
}

.qr-code {
  width: 200px;
  height: 200px;
  border: 4px solid #e3e5e7;
  border-radius: 12px;
}

.qr-status {
  margin-top: 16px;
  padding: 12px;
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.3s;
}

.qr-status.scanning {
  background: #e6f3ff;
  color: #0066cc;
}

.qr-status.success {
  background: #e6f7e6;
  color: #00aa00;
}

.qr-status.expired {
  background: #ffe6e6;
  color: #cc0000;
}

.qr-status .el-icon {
  font-size: 20px;
  margin-bottom: 8px;
}

.qr-actions {
  margin-top: 20px;
}

.qr-actions .el-button {
  width: 120px;
}
</style> 